import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom'
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { Card, Table,  Form, Button, Select, Col, Input, Row, Tabs, DatePicker} from 'antd'
import { 
  merchantBalanceHistory,
} from '@/api/api'
import { deepclone, useSyncCallback } from '@/utils'
import moment from 'moment';
import './index.scss'

let first = false
let orCToken = {}
const Operatelog = (props) => {
  const { route, history } = props
  const { RangePicker } = DatePicker;
  const [searchForm] = Form.useForm();
  const breadcrumbList = ['商户管理','账变记录']
  
  // 布局
  const layout = { sm: 24, md: 12, lg: 12, xl: 7, xxl: 7 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 3, xxl: 3 };
  const labelCol = { sm: 24, md: 6, lg: 6, xl: 6 };
  const wrapperCol = { sm: 24, md: 18, lg: 18, xl: 18 };

  const [values] = useState({
    userName: '',
    ip: '',
  })
  const [userId, setUserId] = useState('');
  const [userName, setuserName] = useState('');
  const [formData, setFormData] = useState(values)
  const [dataSource, setDataSource] = useState([]);
  // 列表总数
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false)

  const handleFinish = async () => {
    try {
      let {countDate, paymentType} = deepclone(formData)
      let params = {
        pageSize,
        currentPage,
        countDate: moment(countDate).format("YYYY-MM-DD"),
        paymentType,
        userId,
      }
      if (typeof orCToken.source === 'function') {
        orCToken.source('终止请求'); //取消请求
      }
      setLoading(true)
      let res = await merchantBalanceHistory(params, orCToken)
      if(res.code === 0) {
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  // 搜索
  const onFinish = () => {
    setCurrentPage(1)
    setPageSize(20)
    searchData()
  }
  const columns = 
  [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text: any, item: any, index: number) => <>{index + 1}</>,
    },
    {
      title: '时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '变动类型',
      dataIndex: 'paymentType',
      key: 'paymentType',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '变动前余额',
      dataIndex: 'beforeAmount',
      key: 'beforeAmount',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '变动数值',
      dataIndex: 'transAmount',
      key: 'transAmount',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '变动后余额',
      dataIndex: 'afterAmount',
      key: 'afterAmount',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
  ];
  //改变搜索条件更新
  useEffect(() => {
    if(first) {
      searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [currentPage, pageSize])
  // 首次更新
  useEffect(() => {
    if(props.params){
    	setUserId(props.params.userId)
      setuserName(props.params.userName)
    }
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  return (
    <div className='operatelog-component'>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='operatelog-main'>
        <Form initialValues={values} form={searchForm} onFinish={(val) => {
          setFormData(val)
          onFinish()
        }}>
          <Card>
            {
              userId
              ?
              <div className="topBtn">
                <span>商户账号: {userName}</span>
                <Button onClick={() => {
                  props.setPageType('index')
                  props.setParams(null)
                }}>返回</Button>
              </div>
              :
              ''
            }
            <Row>
              <Col {...layout}>
                <Form.Item
                  label="日期"
                  name="countDate"
                  className='form-item'
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <DatePicker style={{width: '100%'}} />
                </Form.Item>
              </Col>
              <Col {...layout}>
                <Form.Item
                  label="账变类型"
                  name="paymentType"
                  className='form-item'
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Select options={[
                    {label:'USDT充值',value:'1'},
                    {label:'USDT提现',value:'2'},
                    {label:'转账扣款',value:'3'},
                    {label:'转账加款',value:'4'},
                    {label:'支付订单加款',value:'5'},
                  ]} />
                </Form.Item>
              </Col>
              <Col {...layoutbtn}>
                
                <span className="button-left">
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                    searchForm.resetFields()
                    setFormData(searchForm.getFieldsValue(true))
                    onFinish()
                  }}>
                    重置
                  </Button>
                </span>
              </Col>
            </Row>
          </Card>
        </Form>
        <div className='table-box'>
          <Card>
            <div className='table'>
              <Table 
              loading={loading}
              size='middle'
              bordered
              rowKey={'id'}
              className='antd-table' 
              dataSource={dataSource} 
              pagination={{
                size: 'default',
                current: currentPage,
                total,
                showSizeChanger: true,
                pageSize: pageSize,
                onChange: (page, pagesize) => {
                  setCurrentPage(page)
                  setPageSize(pagesize)
                }
              }}
              columns={columns} />
            </div>
          </Card>
        </div>
      </div>
    </div>
  )
}
export default withRouter(Operatelog)